const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🧪 测试通知功能')
  
  try {
    const { OPENID } = cloud.getWXContext()
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    // 创建测试通知
    const testNotification = {
      type: 'test_notification',
      title: '测试通知',
      content: '这是一条测试通知，用于验证通知功能是否正常工作。',
      targetOpenid: OPENID,
      isRead: false,
      data: {
        testData: '测试数据',
        createTime: new Date()
      },
      createTime: new Date()
    }
    
    console.log('📝 准备插入测试通知:', testNotification)
    
    // 插入通知记录
    const result = await db.collection('user_notifications').add({
      data: testNotification
    })
    
    console.log('✅ 测试通知插入成功:', result._id)
    
    // 查询刚插入的通知
    const queryResult = await db.collection('user_notifications')
      .doc(result._id)
      .get()
    
    console.log('🔍 查询插入的通知:', queryResult.data)
    
    // 查询用户所有通知
    const allNotifications = await db.collection('user_notifications')
      .where({
        targetOpenid: OPENID
      })
      .orderBy('createTime', 'desc')
      .limit(5)
      .get()
    
    console.log('📬 用户所有通知数量:', allNotifications.data.length)
    
    return {
      success: true,
      message: '测试通知发送成功',
      data: {
        notificationId: result._id,
        notification: queryResult.data,
        totalNotifications: allNotifications.data.length,
        allNotifications: allNotifications.data
      }
    }
    
  } catch (error) {
    console.error('❌ 测试通知失败:', error)
    return {
      success: false,
      error: error.message || '测试通知失败'
    }
  }
}
